﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Design;
using Common;

namespace WebSite
{
    public partial class CutIMG : System.Web.UI.Page
    {
        private string _vPath = "/UploadImages/Cut/";
        private string _saveName = "save.jpg";
        public int CutWidth;
        public int CutHeight;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (string.Compare( Request["type"], "team", true ) == 0)
            {
                _vPath = "/UploadImages/TeamCut/";
            }

            //原图片
            string imgsrc = Request["src"];

            if (!imgsrc.StartsWith( "/UploadImages/" ))
            {
                Response.Write( "参数非法" );
                Response.End();
            }

            //"old.jpg";
            string imgPath = imgsrc; // _vPath + imgName;
            initIMG.ImageUrl = imgPath;
            viewIMG.ImageUrl = imgPath;

            CutWidth = StringHelper.Convert( Request["CutWidth"], 200 );
            CutHeight = StringHelper.Convert( Request["CutHeight"], 200 );
        }


        /// <summary>
        /// 裁剪保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void bt_CutIMG_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid) return;
/*
            string[] urls = initIMG.ImageUrl.Split('/');
            string _url = urls.Last()*/;

            _saveName = Guid.NewGuid().ToString( "N" ) + ".jpg";

            // string tempurl = Path.Combine(Server.MapPath(_vPath), _url);
            string tempurl = Server.MapPath( initIMG.ImageUrl );
            string tempurl2 = Path.Combine(Server.MapPath(_vPath), _saveName);
            int startX = int.Parse(hidden_x1.Value);
            int startY = int.Parse(hidden_y1.Value);
            int width = int.Parse(hidden_Iwidth.Value);
            int height = int.Parse(hidden_Iheight.Value);
            saveIMG(startX, startY, width, height, tempurl, tempurl2);

            string callbackFunc = StringHelper.Convert( Request["callback"], "cutCallback" );

            //ScriptManager.RegisterStartupScript(this.Page, GetType(), "js", "alert('裁剪成功，路径：'+unescape('" + tempurl2 + "'))", true);
            ScriptManager.RegisterStartupScript( this.Page, GetType(), "js", "window.parent.window." + callbackFunc + "('" + _vPath + _saveName + "');", true );
            return;
        }


        #region 私有方法

        /// <summary>
        /// 缩小裁剪图片
        /// </summary>
        /// <param name="startX"></param>
        /// <param name="startY"></param>
        /// <param name="int_Width">要缩小裁剪图片宽度</param>
        /// <param name="int_Height">要缩小裁剪图片长度</param>
        /// <param name="input_ImgUrl">要处理图片路径</param>
        /// <param name="out_ImgUrl">处理完毕图片路径</param>
        public void saveIMG(int startX, int startY, int int_Width, int int_Height, string input_ImgUrl, string out_ImgUrl)
        {
            // ＝＝＝上传标准图大小＝＝＝
            int int_Standard_Width = CutWidth; // 200
            int int_Standard_Height = CutHeight; // 200

            int Reduce_Width = 0; // 缩小的宽度
            int Reduce_Height = 0; // 缩小的高度
            int CutOut_Width = 0; // 裁剪的宽度
            int CutOut_Height = 0; // 裁剪的高度
            int level = 80; //缩略图的质量 1-100的范围

            // ＝＝＝获得缩小，裁剪大小＝＝＝
            if (int_Standard_Height * int_Width / int_Standard_Width > int_Height)
            {
                Reduce_Width = int_Width;
                Reduce_Height = int_Standard_Height * int_Width / int_Standard_Width;
                CutOut_Width = int_Width;
                CutOut_Height = int_Height;
            }
            else if (int_Standard_Height * int_Width / int_Standard_Width < int_Height)
            {
                Reduce_Width = int_Standard_Width * int_Height / int_Standard_Height;
                Reduce_Height = int_Height;
                CutOut_Width = int_Width;
                CutOut_Height = int_Height;
            }
            else
            {
                Reduce_Width = int_Width;
                Reduce_Height = int_Height;
                CutOut_Width = int_Width;
                CutOut_Height = int_Height;
            }

            // ＝＝＝通过连接创建Image对象＝＝＝
            /*System.Drawing.Image oldimage = System.Drawing.Image.FromFile(input_ImgUrl);
            oldimage.Save(Server.MapPath(_vPath + "temp.jpg"));
            oldimage.Dispose();*/

            //// ＝＝＝缩小图片＝＝＝
            // System.Drawing.Image thumbnailImage = oldimage.GetThumbnailImage(Reduce_Width, Reduce_Height, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);

            Bitmap bm = new Bitmap( input_ImgUrl );

            // ＝＝＝处理JPG质量的函数＝＝＝
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo ici = null;
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType == "image/jpeg")
                {
                    ici = codec;
                    break;
                }

            }
            EncoderParameters ep = new EncoderParameters();
            ep.Param[0] = new EncoderParameter(Encoder.Quality, (long)level);

            // ＝＝＝裁剪图片＝＝＝
            Rectangle cloneRect = new Rectangle(startX, startY, CutOut_Width, CutOut_Height);
            PixelFormat format = bm.PixelFormat;
            Bitmap cloneBitmap = bm.Clone(cloneRect, format);

            // ＝＝＝保存图片＝＝＝
            cloneBitmap.Save(out_ImgUrl, ici, ep);
            bm.Dispose();
        }

        public bool ThumbnailCallback()
        {
            return false;
        }



        #endregion







    }
}